﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DHLPricing.OrderServices;
using System.IO;
using NPOI.HSSF.UserModel;

namespace DHLPricing.OrderInfo
{
    public partial class OrdersManage : Form
    {
        public static ArrayOfString SearchOrderNumbers = new ArrayOfString();//查询的OrderNumber
        static List<Orders> ordersList = new List<Orders>();//查询结果

        public OrdersManage()
        {
            InitializeComponent();
            txtBeginOrderTime.Text = "2006-12-1";

            sltStatus.Items.Add(new OrderStatus() { Value = -1, Text = "ShowALL" });
            sltStatus.Items.Add(new OrderStatus() { Value = 0, Text = "未发货" });
            sltStatus.Items.Add(new OrderStatus() { Value = 99, Text = "已发货" });
            sltStatus.DisplayMember = "Text";
            sltStatus.ValueMember = "Value";
            sltStatus.SelectedIndex = 0;

            openSearchOrderNumbersFileDialog.Filter = "txt文件|*.txt";
            saveOrderFileDialog.Filter = "excel文件|*.xls";
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            BindOrderData();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OrderInfo.OrderNumberInput orderNumberInput = new OrderNumberInput();
            orderNumberInput.Owner = this;
            orderNumberInput.ShowDialog();

            #region 不用浏览文件的方式
            //DialogResult result = openSearchOrderNumbersFileDialog.ShowDialog();
            //if (result == System.Windows.Forms.DialogResult.OK && openSearchOrderNumbersFileDialog.CheckFileExists && openSearchOrderNumbersFileDialog.CheckPathExists)
            //{
            //    txtOrderNumber.Text = openSearchOrderNumbersFileDialog.FileName;
            //    using (StreamReader sr = new StreamReader(openSearchOrderNumbersFileDialog.FileName))
            //    {
            //        string searchOrderNumbers = sr.ReadToEnd();
            //        SearchOrderNumbers.AddRange(searchOrderNumbers.Split(new string[] { ",", "，", ";", "；", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList());
            //    }            
            //}
            //else
            //{
            //    MessageBox.Show("打开文件失败。");
            //}
            #endregion
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            DialogResult result = saveOrderFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                ExportErrorOrders(saveOrderFileDialog.FileName);
            }
            else
            {
                MessageBox.Show("选择的保存文件失败。");
            }
        }

        private static void ExportErrorOrders(string fileName)
        {
            //创建xls文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建sheet表单，默认名称为sheet1
            HSSFSheet sheet = workbook.CreateSheet("导出的订单数据");

            //创建行，并设定第一行的表头
            HSSFRow rowTitle = sheet.CreateRow(0);

            rowTitle.CreateCell(0, HSSFCellType.STRING).SetCellValue("ID");
            rowTitle.CreateCell(1, HSSFCellType.STRING).SetCellValue("运单号");
            rowTitle.CreateCell(2, HSSFCellType.STRING).SetCellValue("转单号");
            rowTitle.CreateCell(3, HSSFCellType.STRING).SetCellValue("渠道");
            rowTitle.CreateCell(4, HSSFCellType.STRING).SetCellValue("目的地");
            rowTitle.CreateCell(5, HSSFCellType.STRING).SetCellValue("分区");
            rowTitle.CreateCell(6, HSSFCellType.STRING).SetCellValue("品名");
            rowTitle.CreateCell(7, HSSFCellType.STRING).SetCellValue("件数");
            rowTitle.CreateCell(8, HSSFCellType.STRING).SetCellValue("实量");
            rowTitle.CreateCell(9, HSSFCellType.STRING).SetCellValue("状态");
            rowTitle.CreateCell(10, HSSFCellType.STRING).SetCellValue("批次");
            rowTitle.CreateCell(11, HSSFCellType.STRING).SetCellValue("航班");
            rowTitle.CreateCell(12, HSSFCellType.STRING).SetCellValue("订单时间");
            rowTitle.CreateCell(13, HSSFCellType.STRING).SetCellValue("价格");

            int rowNum = 0;
            foreach (Orders temp in ordersList)
            {
                HSSFRow rowContent = sheet.CreateRow(rowNum + 1);//创建内容行

                //对第1行对应的单元格分别设定单元格内容属性和填充对应的值
                rowContent.CreateCell(0, HSSFCellType.STRING).SetCellValue(temp.ID);
                rowContent.CreateCell(1, HSSFCellType.STRING).SetCellValue(temp.OrderNumberRef);
                rowContent.CreateCell(2, HSSFCellType.STRING).SetCellValue(temp.OrderNumber);
                rowContent.CreateCell(3, HSSFCellType.STRING).SetCellValue(temp.ChannelCode);
                rowContent.CreateCell(4, HSSFCellType.STRING).SetCellValue(temp.CountryCN);
                rowContent.CreateCell(5, HSSFCellType.STRING).SetCellValue(temp.Zone.ToString());
                rowContent.CreateCell(6, HSSFCellType.STRING).SetCellValue(temp.ItemType.Value == 0 ? "DOC" : "其他");
                rowContent.CreateCell(7, HSSFCellType.STRING).SetCellValue(temp.Pieces.ToString());
                rowContent.CreateCell(8, HSSFCellType.STRING).SetCellValue(temp.RealWeight.ToString());
                rowContent.CreateCell(9, HSSFCellType.STRING).SetCellValue(temp.Status.ToString());
                rowContent.CreateCell(10, HSSFCellType.STRING).SetCellValue(temp.BatchInfo);
                rowContent.CreateCell(11, HSSFCellType.STRING).SetCellValue(temp.FlightInfo);
                rowContent.CreateCell(12, HSSFCellType.STRING).SetCellValue(temp.OrderTime.ToString());
                rowContent.CreateCell(13, HSSFCellType.STRING).SetCellValue(temp.Price.ToString());
                rowNum++;//动态增加行号
            }

            //写入excel文件
            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);//把流写入文件
            }

            MessageBox.Show(rowNum - 1 + "条数据导出成功");//实际导出的数据比定义的行号少1            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            OrderAddOrUpdate orderAddOrUpdate = new OrderAddOrUpdate();
            orderAddOrUpdate.Show();
        }

        /// <summary>
        /// 设定数据需要查询的转单号数据
        /// </summary>
        /// <param name="SearchOrderNumbers"></param>
        public void SetSearchOrderNumbersValue(string SearchOrderNumbers)
        {
            txtOrderNumber.Text = SearchOrderNumbers;
        }

        private void txtOrderNumber_TextChanged(object sender, EventArgs e)
        {
            SearchOrderNumbers = new ArrayOfString();
            SearchOrderNumbers.AddRange(txtOrderNumber.Text.Split(new string[] { ",", "，", ";", "；", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList());
        }

        private void dataGridOrders_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int OrderID = Convert.ToInt32(dataGridOrders.Rows[e.RowIndex].Cells["ID"].Value);
            Orders order = ordersList.Where(o => o.ID == OrderID).FirstOrDefault();

            OrderAddOrUpdate orderAddOrUpdate = new OrderAddOrUpdate() { CurrentOrder = order };
            orderAddOrUpdate.Owner = this;
            orderAddOrUpdate.Show();
            orderAddOrUpdate.BindEditData();
        }

        private void sltSelectALL_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridOrders.Rows.Count; i++)
            {
                dataGridOrders.Rows[i].Cells[0].Value = sltSelectALL.Checked;
            }
        }

        private void dataGridOrders_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //for (int i = 0; i < dataGridOrders.Rows.Count; i++)
            //{
            //    if (dataGridOrders.Rows[i].Cells["Status"].Value.ToString() == "0")
            //        dataGridOrders.Rows[i].Cells["Status"].Value = "未发货";
            //    else if (dataGridOrders.Rows[i].Cells["Status"].Value.ToString() == "99")
            //        dataGridOrders.Rows[i].Cells["Status"].Value = "已发货";
            //}
        }

        private void dataGridOrders_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //if (e.ColumnIndex == dataGridOrders.Columns["Status"].Index)
            //{
            //    if (e.Value.ToString().Trim() == "0")
            //    {
            //        e.Value = "未发货";
            //    }
            //    else if (e.Value.ToString().Trim() == "99")
            //    {
            //        e.Value = "已发货";
            //    }
            //}
        }

        private void btnBatch_Click(object sender, EventArgs e)
        {
            StringBuilder OrderNumbers = new StringBuilder();
            for (int i = 0; i < dataGridOrders.Rows.Count; i++)
            {
                if (dataGridOrders.Rows[i].Cells[0].Value != null && (bool)dataGridOrders.Rows[i].Cells[0].Value)
                {
                    OrderNumbers.Append(dataGridOrders.Rows[i].Cells["OrderNumber"].Value + ",");
                }
            }

            if (string.IsNullOrEmpty(OrderNumbers.ToString()))
            {
                MessageBox.Show("请先在下方列表中勾选需要填写批次信息的数据。");
            }
            else
            {
                BatchInfoInput batchInfoInput = new BatchInfoInput();
                batchInfoInput.Owner = this;
                batchInfoInput.OrderNumbers = OrderNumbers.ToString().TrimEnd(',');
                batchInfoInput.ShowDialog();
            }
        }

        /// <summary>
        /// 绑定订单数据
        /// </summary>
        public void BindOrderData()
        {
            string channelCode = txtChannelCode.Text;
            string customerCode = txtCustomerCode.Text;
            DateTime beginOderTime = Convert.ToDateTime(txtBeginOrderTime.Text);
            DateTime endOrerTime = Convert.ToDateTime(txtEndOrderTime.Text);
            string batchInfo = txtBatchInfo.Text;

            if (!string.IsNullOrEmpty(txtOrderNumber.Text) && SearchOrderNumbers.Count == 0)
            {
                SearchOrderNumbers.Add(txtOrderNumber.Text);
            }

            int? status = null;

            if (((OrderStatus)sltStatus.SelectedItem).Value != -1)
            {
                status = ((OrderStatus)sltStatus.SelectedItem).Value;
            }
            OrderServices.OrderServiceSoapClient client = new OrderServices.OrderServiceSoapClient();
            ordersList = client.SearchOrders(channelCode, customerCode, beginOderTime, endOrerTime, SearchOrderNumbers, status, batchInfo).ToList();

            dataGridOrders.AutoGenerateColumns = false;
            dataGridOrders.DataSource = ordersList;
        }

        private void btnShipping_Click(object sender, EventArgs e)
        {
            List<Orders> toShippingOrder = new List<Orders>();
            StringBuilder OrderNumbers = new StringBuilder();
            OrderServices.ArrayOfString orderNumbersArray = new ArrayOfString();
            string result = string.Empty;

            for (int i = 0; i < dataGridOrders.Rows.Count; i++)
            {
                if (dataGridOrders.Rows[i].Cells[0].Value != null && (bool)dataGridOrders.Rows[i].Cells[0].Value)
                {
                    toShippingOrder.Add(ordersList.Where(o => o.OrderNumber == dataGridOrders.Rows[i].Cells["OrderNumber"].Value.ToString()).FirstOrDefault());
                     OrderNumbers.Append(dataGridOrders.Rows[i].Cells["OrderNumber"].Value + ",");
                }
            }
            if (toShippingOrder.Count == 0)
            {
                MessageBox.Show("请先在下方列表中勾选需要发运的数据。");
                return;
            }

            if (toShippingOrder.Where(o => string.IsNullOrEmpty(o.BatchInfo)).Count() > 0)
            {
                MessageBox.Show("没有填写批次信息的订单不能被发送，请先取消选择这些订单。");
                return;
            }

            if (MessageBox.Show("确定对以下订单进行发运吗？\n" + OrderNumbers.ToString().TrimEnd(','), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                orderNumbersArray.AddRange(toShippingOrder.Select(o=>o.OrderNumber));
                OrderServices.OrderServiceSoapClient client = new OrderServiceSoapClient();
                try
                {
                    result = client.ShippingOrders(orderNumbersArray);
                    if (result == "0")
                    {
                        MessageBox.Show("发运成功。");
                        BindOrderData();
                    }
                    else
                    {
                        MessageBox.Show("发运失败，失败原因：" + result);
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("发运失败，失败原因：" + ex.Message);
                }
            }
        }
    }

    public class OrderStatus
    {
        public int Value { get; set; }
        public string Text { get; set; }
    }
}
